package excel;

import com.kis.model.channel.ChannelCountry;
import com.kis.model.channel.Country;
import com.kis.model.channel.SendType;
import com.kis.service.commonService.CommonService;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Stream;

/**
 * Created by wanglong on 15-12-17.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring/applicationContext.xml"})
public class ChannelCountryImport {
    @Autowired
    private CommonService commonService;

    @Test
    public void testImp() throws Exception {
        InputStream is = new FileInputStream("/home/wanglong/work/data/wl.xls");
        String[] countries = getSendTypeData(is,34);
        System.out.println(countries.length);
        List<Country> countryList = commonService.getAll(Country.class,null,null);
        Map<String,Long> countryMap = new HashMap<>();
        countryList.forEach(c->countryMap.put(c.getNameCn(),c.getId()));
        List<ChannelCountry> channelCountryList = new ArrayList<ChannelCountry>();
        Arrays.asList(countries).forEach(c->channelCountryList.add(new ChannelCountry(countryMap.get(c),22L)));
        Stream<ChannelCountry> channelCountryList1 = channelCountryList.stream().filter(channelCountry -> null!=channelCountry.getCountryId());
        System.out.println(channelCountryList.size());
        commonService.batchAddObject(Arrays.asList(channelCountryList1.toArray()));
    }

    public String[] getSendTypeData(InputStream is, int readline) throws Exception {
        String[] result;
        POIFSFileSystem fs = new POIFSFileSystem(is);
        HSSFWorkbook wb = new HSSFWorkbook(fs);
        HSSFSheet st = wb.getSheetAt(0);
        String country = st.getRow(readline).getCell(5).toString();
        result = country.split(",");
        return result;
    }
}
